package com.yimi.yinhepda.views.createPackage_module;

import android.content.DialogInterface;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.pda.ym.utils.SysInfo;
import com.yimi.yinhepda.R;
import com.yimi.yinhepda.adapter.BuildScanByHandAdapter;
import com.pda.ym.callbacks.UICallBack;
import com.yimi.yinhepda.db.dao.BuildPckScanTableDao;
import com.yimi.yinhepda.db.table.BuildPckScanTable;
import com.yimi.yinhepda.entity.bean.AddEntity;
import com.yimi.yinhepda.entity.request.QueryWaybillByChildNoRequest;
import com.yimi.yinhepda.entity.response.BuildPackageDetailResponse;
import com.yimi.yinhepda.entity.response.QueryWaybillByChildNoResponse;
import com.yimi.yinhepda.entity.response.WaybillInfo;
import com.yimi.yinhepda.event.CountEvent;
import com.pda.ym.net.NetRequest;
import com.yimi.yinhepda.utils.Common;
import com.pda.ym.utils.Constants;
import com.yimi.yinhepda.utils.IntentUtils;
import com.pda.uce.commom.util.MyDialog;
import com.pda.ym.utils.SharedPreferUtil;
import com.pda.ym.utils.SoundVibratorManager;
import com.pda.ym.utils.StringUtils;
import com.yimi.yinhepda.base.BaseInitActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.Bind;

/**
 * @author 000432
 * @date 2017/4/10 0010
 *
 * 手动添加条码页面( 建包扫描页面 )
 */
public class CreateAddByHandActivity extends BaseInitActivity {
  /** 标题栏左边 */
  @Bind(R.id.title) TextView mTvTitle;
  /** 标题栏中间 */
  @Bind(R.id.num) TextView mTvNum;
  /** 添加按钮 */
  @Bind(R.id.manual_add_btn) Button mBtnAdd;
  /** 条码输入框 */
  @Bind(R.id.load_addchildwaybill_ed) EditText mEtBarcode;
  @Bind(R.id.add_chidlwaybill_listview) ListView mListView;
  @Bind(R.id.manaul_add_count) TextView mTvAddTip;
  @Bind(R.id.add_childwaybill_back) Button mImgAddBack;
  @Bind(R.id.add_childwaybill_ok) Button mImgAddOk;

  private BuildPckScanTableDao mBuildPckScanTableDao;
  private List<AddEntity> mAddEntityList = new ArrayList<>();
  private BuildScanByHandAdapter mAdapter;

  /** 手加票 */
  private int mHandAddBill;
  /** 手加件 */
  private int mHandAdditem;
  /** 建包目的地 */
  private String destCode;
  private String destName;
  /** 任务号 */
  private String taskNo;
  /** 总的未上传数量 */
  private int totalNotUploadNum;

  private List<BuildPackageDetailResponse.StockInfo> buildList;

  @Override public String getPageName() {
    return getString(R.string.page_create_addbyhand);
  }

  public CreateAddByHandActivity() {
    super(true);
  }

  @Override protected void handleBarCode(String result) {
    super.handleBarCode(result);
    if (result == null) {
      SoundVibratorManager.playSound(2);
      showToast("运单号扫描失败");
    } else {
      mEtBarcode.setText(result);
    }
  }

  @Override public int getContentViewId() {
    return R.layout.activity_add_childbillway;
  }

  @Override public void initView(Bundle savedInstanceState) {
    EventBus.getDefault().register(this);
    mTvTitle.setText(getString(R.string.hand_add_title));
  }

  @Override public void initEvent() {
    mBtnAdd.setOnClickListener(this);
    mImgAddBack.setOnClickListener(this);
    mImgAddOk.setOnClickListener(this);
  }

  @Override public void initData() {
    //目的地
    destCode = getIntent().getStringExtra(IntentUtils.BUILD_DEST);
    destName = getIntent().getStringExtra(IntentUtils.BUILD_DEST_NAME);
    taskNo = getIntent().getStringExtra(IntentUtils.BUILD_PKG_TASK_NO);
    buildList = CreatePackageScanActivity.buildList;
    //数据库对象
    mBuildPckScanTableDao = new BuildPckScanTableDao();
    /** 查询未上传数据*/
    totalNotUploadNum = mBuildPckScanTableDao.queryNotUploadDataNum(taskNo);
    mTvNum.setText(totalNotUploadNum + "");

    //列表
    mAdapter = new BuildScanByHandAdapter(this, mAddEntityList);
    mListView.setAdapter(mAdapter);
  }

  @Override public void onClick(View v) {
    super.onClick(v);
    switch (v.getId()) {
      case R.id.manual_add_btn:
        //添加按钮
        startAddBarData();
        break;
      case R.id.add_childwaybill_back:
        //返回按钮
        activityBackMethod();
        break;
      case R.id.add_childwaybill_ok:
        //确定按钮
        activityBackMethod();
        break;
      default:
        break;
    }
  }

  /***
   * 开始添加条码的操作
   */
  private void startAddBarData() {

    String barCodeStr = mEtBarcode.getText().toString().trim();

    //判断单号长度
    if (!StringUtils.isWaybillNo(barCodeStr)) {
      SoundVibratorManager.playSound(2);
      showToast("运单号不规范");
      return;
    }

    /***
     * buildList 是扫描页面全局的
     */
    if (buildList != null) {
      for (int i = 0; i < buildList.size(); i++) {
        //当前行的运单信息，包括子单的集合
        BuildPackageDetailResponse.StockInfo currentItemInfo = buildList.get(i);
        /** 判断子单是不是以主单开始的,减少循环次数*/
        if (!barCodeStr.startsWith(String.valueOf(currentItemInfo.getWaybillNo()))) {
          continue;
        }
        //子单的集合
        List<BuildPackageDetailResponse.ChildInfo> childList = currentItemInfo.getChildList();
        //循环子单的集合
        for (BuildPackageDetailResponse.ChildInfo child : childList) {
          //子单字符串
          String childWaybillno = child.getChildWaybillNo();
          //扫描子单和集合中一个子单相同
          if (barCodeStr.equals(childWaybillno)) {
            Integer flag = child.getFlag();
            if (flag == 1) {
              SoundVibratorManager.playSound(2);
              showToast("重复扫描!");
            } else {
              String remark = "1";
              if (currentItemInfo.getRemark() != null) {
                if (currentItemInfo.getRemark().equals("2")) {
                  remark = "2";
                }
              }
              /** 扫描数据插入到表中*/
              if (insertScannedData(currentItemInfo, childWaybillno, remark) < 0) {
                SoundVibratorManager.playSound(2);
                showToast("插入数据库失败!");
                return;
              }

              totalNotUploadNum++;
              mTvNum.setText(totalNotUploadNum + "");
              EventBus.getDefault().post(new CountEvent(totalNotUploadNum));

              SoundVibratorManager.playSound(1);

              /** 设置该子单为已扫描的状态*/
              child.setFlag(1);

              /** 添加到列表*/
              AddEntity addEntity = new AddEntity();
              addEntity.setWaybillNum(currentItemInfo.getWaybillNo());
              addEntity.setChildwayBillNum(child.getChildWaybillNo());
              mAddEntityList.add(addEntity);
              mAdapter.notifyDataSetChanged();

              /** 刷新手动添加票和件*/
              mHandAddBill = getHandAddBill();
              mHandAdditem++;
              mTvAddTip.setText(String.format(getString(R.string.hand_add_num), mHandAddBill, mHandAdditem));
            }

            /** 更新当前行到第一行*/
            buildList.remove(i);
            buildList.add(0, currentItemInfo);
            return;
          }
        }
      }
    }

    SoundVibratorManager.playSound(2);
    showToast("运单号不在列表中！");

    /** 条码不在任务内, 后面进行路由判断，是否强扫*/
    //downloadWaybillNo(barCodeStr);
  }

  /**
   * 子单下载主单
   */
  private void downloadWaybillNo(final String result) {
    setScannerEnabled(false);
    showPgDlg("正在子单下载主单...");

    //扫描数据上传完后  调完成任务
    QueryWaybillByChildNoRequest mQueryWaybillByChildNoRequest = new QueryWaybillByChildNoRequest();
    mQueryWaybillByChildNoRequest.setChildWaybillNo(result);

    //        OkHttpUtils
    //                .get()
    //                .url(Constants.URL_FORCE_SCAN)
    //                .addParams("childWaybillNo", result)
    ////                .postString()
    ////                .url(Constants.URL_FORCE_SCAN)
    ////                .content(new Gson().toJson(mQueryWaybillByChildNoRequest))
    ////                .mediaType(MediaType.parse("application/json; charset=utf-8"))
    //                .build()
    //                .execute(new ObjectCallback<QueryWaybillByChildNoResponse>() {
    //
    //                    @Override
    //                    public void onResponse(final QueryWaybillByChildNoResponse response, int id) {
    //                        if (response==null||!response.isSuccess()) {
    //                            //开启扫描
    //                            setScannerEnabled(true);
    //                            dismissPgDlg();
    //                            SoundVibratorManager.playSound(2);
    //                            if(response!=null&&response.getErrorMessages()!=null&&response.getErrorMessages().length>0){
    //                                showToast(response.getErrorMessages()[0]);
    //                            }else{
    //                                showToast("没有该条码的主单信息!");
    //                            }
    //                            return;
    //                        }
    //
    //                        //路由验证
    //                        if (!waybillRouteWrong(response.getData().getRouteCode(), destCode)) {
    //                            //合并数据到内存，并插入当前条码到数据库
    //                            merge(response.getData(), result);
    //                        } else {
    //                            MyDialog dialog = new MyDialog(CreateAddByHandActivity.this);
    //                            dialog.setDialogType(MyDialog.DialogType.ALERT_DIALOG);
    //                            dialog.setTitle("系统提示");
    //                            dialog.setMessage("请核对正确目的站是否扫描？");
    //                            dialog.setPositiveClickListener(
    //                                    R.drawable.btn_login_selector, "确定",
    //                                    new DialogInterface.OnClickListener() {
    //                                        @Override
    //                                        public void onClick(DialogInterface dialog,
    //                                                            int which) {
    //                                            dialog.dismiss();
    //                                            //合并数据到内存，并插入当前条码到数据库
    //                                            merge(response.getData(), result);
    //                                        }
    //                                    });
    //                            dialog.setNegativeClickListener(
    //                                    R.drawable.btn_login_selector, "取消",
    //                                    new DialogInterface.OnClickListener() {
    //                                        @Override
    //                                        public void onClick(DialogInterface dialog, int which) {
    //                                            dialog.dismiss();
    //                                        }
    //                                    });
    //                            dialog.show();
    //                        }
    //                        //开启扫描
    //                        setScannerEnabled(true);
    //                        dismissPgDlg();
    //                    }
    //
    //                    @Override
    //                    public void onError(Call call, Exception e, int id) {
    //                        dismissPgDlg();
    //                        SoundVibratorManager.playSound(2);
    //                        showToast("子单下载主单失败!");
    //                        setScannerEnabled(true);
    //                    }
    //                });

    Map param = new HashMap();
    param.put("childWaybillNo", result);

    new NetRequest().setMethod(NetRequest.Method.GET)
        .setUrl(Constants.URL_FORCE_SCAN)
        .setParams(param)
        .setResponsClazz(QueryWaybillByChildNoResponse.class)
        .execute(new UICallBack() {
          @Override public void onError(String msg) {
            dismissPgDlg();
            SoundVibratorManager.playSound(2);
            if (msg != null) {
              showToast("子单下载主单失败:" + msg);
            } else {
              showToast("子单下载主单失败!");
            }
            setScannerEnabled(true);
          }

          @Override public void onSuccess(Object obj) {
            final QueryWaybillByChildNoResponse response = (QueryWaybillByChildNoResponse) obj;

            //路由验证
            if (!Common.waybillRouteWrong(response.getData().getRouteCode(), destCode)) {
              //合并数据到内存，并插入当前条码到数据库
              merge(response.getData(), result);
            } else {
              MyDialog dialog = new MyDialog(CreateAddByHandActivity.this);
              dialog.setIcon(R.drawable.alert);
              dialog.setDialogType(MyDialog.DialogType.ALERT_DIALOG);
              dialog.setTitle("系统提示");
              dialog.setMessage("请核对正确目的站是否扫描？");
              dialog.setPositiveClickListener( "确定", new DialogInterface.OnClickListener() {
                @Override public void onClick(DialogInterface dialog, int which) {
                  dialog.dismiss();
                  //合并数据到内存，并插入当前条码到数据库
                  merge(response.getData(), result);
                }
              });
              dialog.setNegativeClickListener(R.drawable.btn_login_selector, "取消", new DialogInterface.OnClickListener() {
                @Override public void onClick(DialogInterface dialog, int which) {
                  dialog.dismiss();
                }
              });
              dialog.show();
            }
            //开启扫描
            setScannerEnabled(true);
            dismissPgDlg();
          }
        });
  }

  /**
   * 合并数据到内存，并插入当前条码到数据库
   */
  private void merge(WaybillInfo data, String result) {

    BuildPackageDetailResponse.StockInfo stockInfo = new BuildPackageDetailResponse.StockInfo();
    stockInfo.setWaybillNo(data.getWaybillNo() + "");
    stockInfo.setPackageNo("");
    stockInfo.setSrcPiecesNum(data.getQuantity());
    stockInfo.setPiecesNum(data.getNowInventory());
    stockInfo.setWeight(data.getRealWeight());
    stockInfo.setChargedWeight(data.getChargeableWeight());
    stockInfo.setVolume(data.getVolume());
    stockInfo.setAreaCode("");
    stockInfo.setBillType("");
    stockInfo.setWaybillRoute(data.getRouteCode());
    stockInfo.setRemark("2");

    List<BuildPackageDetailResponse.ChildInfo> childList = new ArrayList<BuildPackageDetailResponse.ChildInfo>();
    for (int i = 0; i < data.getQuantity(); i++) {
      String childWaybillNo = data.getWaybillNo() + String.format("%03d", i + 1);
      BuildPackageDetailResponse.ChildInfo mChildInfo = new BuildPackageDetailResponse.ChildInfo();
      if (result.equals(childWaybillNo)) {
        mChildInfo.setFlag(1);
      } else {
        mChildInfo.setFlag(0);
      }
      mChildInfo.setChildWaybillNo(childWaybillNo);
      childList.add(mChildInfo);
    }
    //子单集合加入到运单对象中
    stockInfo.setChildList(childList);

    //强扫去除重复运单
    Iterator<BuildPackageDetailResponse.StockInfo> it = buildList.iterator();
    while (it.hasNext()) {
      BuildPackageDetailResponse.StockInfo stockInfo1 = it.next();
      if (stockInfo1.getWaybillNo().equals(data.getWaybillNo().toString())) {
        stockInfo.setPiecesNum(stockInfo1.getPiecesNum());
        it.remove();
        break;
      }
    }

    //扫描的子单插入到数据库
    if (insertScannedData(stockInfo, result, "2") < 0) {
      SoundVibratorManager.playSound(2);
      showToast("插入数据失败!");
      return;
    }

    //未上传数据
    totalNotUploadNum++;
    mTvNum.setText(totalNotUploadNum + "");
    EventBus.getDefault().post(new CountEvent(totalNotUploadNum));

    SoundVibratorManager.playSound(1);

    Collections.sort(buildList);
    buildList.add(0, stockInfo);

    /** 添加到列表*/
    AddEntity addEntity = new AddEntity();
    addEntity.setWaybillNum(data.getWaybillNo() + "");
    addEntity.setChildwayBillNum(result + "");
    mAddEntityList.add(addEntity);
    mAdapter.notifyDataSetChanged();

    /** 刷新手动添加票和件*/
    mHandAddBill = getHandAddBill();
    mHandAdditem++;
    mTvAddTip.setText(String.format(getString(R.string.hand_add_num), mHandAddBill, mHandAdditem));
  }

  /**
   * 手动添加的票数
   */
  private int getHandAddBill() {
    Set<String> set = new HashSet<String>();
    for (AddEntity item : mAddEntityList) {
      set.add(item.getWaybillNum());
    }
    return set.size();
  }

  /**
   * 插入已经扫描的数据到表中
   *
   * @param currentItemInfo 当前运单号的相关信息
   */
  private int insertScannedData(BuildPackageDetailResponse.StockInfo currentItemInfo, String childWaybillNo, String remark) {

    BuildPckScanTable buildPckScanTable = new BuildPckScanTable();
    //开单件数
    buildPckScanTable.setSrcPiecesNum(currentItemInfo.getSrcPiecesNum());
    //库存件数
    buildPckScanTable.setPiecesNum(currentItemInfo.getPiecesNum());
    //开单重量
    buildPckScanTable.setWeight(currentItemInfo.getWeight());
    //开单体积
    buildPckScanTable.setVolume(currentItemInfo.getVolume());
    //计费重量
    buildPckScanTable.setChargedWeight(currentItemInfo.getChargedWeight());
    buildPckScanTable.setTaskNo(taskNo);
    buildPckScanTable.setPackageNo(currentItemInfo.getPackageNo());
    //目的地编号
    buildPckScanTable.setDestDeptCode(destCode);
    //目的地名称
    buildPckScanTable.setDestDeptName(destName);
    //当前站点编号
    buildPckScanTable.setSrcDeptCode(SharedPreferUtil.getInstance().getValue(Common.DEPT_CODE));
    //当前站点名称
    buildPckScanTable.setSrcDeptName(SharedPreferUtil.getInstance().getValue(Common.DEPT_NAME));
    //路由
    buildPckScanTable.setRoute(currentItemInfo.getWaybillRoute());
    //操作人员工号
    buildPckScanTable.setOperEmpCode(SharedPreferUtil.getInstance().getValue(Common.USER_CODE));
    //操作人员姓名
    buildPckScanTable.setOperEmpName(SharedPreferUtil.getInstance().getValue(Common.USER_NAME));
    //数据库时间, 3天
    buildPckScanTable.setOperTime(Constants.GetSysTime());
    //扫描时间,
    buildPckScanTable.setScanTime(Constants.GetScanTime());
    //主单号
    buildPckScanTable.setWaybillNo(currentItemInfo.getWaybillNo());
    //子单号
    buildPckScanTable.setChildWaybillNo(childWaybillNo);
    //装卸车类型  操作类型，操作码:3 -装包??
    buildPckScanTable.setOperTypeCode(0);
    //输入方式 1-PDA扫描输入,2-手动输入
    buildPckScanTable.setInputType(2);
    //强扫标记 或者备注??
    buildPckScanTable.setRemark(remark);
    //到达库区
    buildPckScanTable.setAreaCode(currentItemInfo.getAreaCode());
    //所属网点
    buildPckScanTable.setDeptCode(SharedPreferUtil.getInstance().getValue(Common.DEPT_CODE));
    buildPckScanTable.setDeviceCode(SysInfo.getInstance().getImei());
    buildPckScanTable.setIsUpload(0);
    int result = 0;
    try {
      result = mBuildPckScanTableDao.insert(buildPckScanTable);
    } catch (Exception e) {
      e.printStackTrace();
      result = -1;
    }
    return result;
  }

  @Subscribe(threadMode = ThreadMode.MAIN) public void onMainEventBus(CountEvent countEvent) {
    mTvNum.setText(countEvent.getCount() + "");
  }

  @Override protected void onDestroy() {
    super.onDestroy();
    EventBus.getDefault().unregister(this);
  }

  @Override public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
      activityBackMethod();
    }
    return false;
  }

  private void activityBackMethod() {
    finish();
  }
}
